export class WordHelper {
  private static isWordAvailable(): boolean {
    return typeof Office !== 'undefined' && 
           typeof Office.context !== 'undefined' && 
           Office.context.document !== null;
  }

  public static async insertText(text: string, location: Word.InsertLocation = Word.InsertLocation.replace): Promise<void> {
    if (!this.isWordAvailable()) {
      throw new Error('Word is not available');
    }

    return Word.run(async (context) => {
      const selection = context.document.getSelection();
      selection.insertText(text, location);
      await context.sync();
    });
  }

  public static async getSelectedText(): Promise<string> {
    if (!this.isWordAvailable()) {
      throw new Error('Word is not available');
    }

    return Word.run(async (context) => {
      const selection = context.document.getSelection();
      selection.load('text');
      await context.sync();
      return selection.text;
    });
  }

  public static async replaceSelectedText(newText: string): Promise<void> {
    if (!this.isWordAvailable()) {
      throw new Error('Word is not available');
    }

    return Word.run(async (context) => {
      const selection = context.document.getSelection();
      selection.insertText(newText, Word.InsertLocation.replace);
      await context.sync();
    });
  }

  public static async addContentControl(text: string, tag?: string): Promise<void> {
    if (!this.isWordAvailable()) {
      throw new Error('Word is not available');
    }

    return Word.run(async (context) => {
      const selection = context.document.getSelection();
      const contentControl = selection.insertContentControl();
      contentControl.insertText(text, Word.InsertLocation.replace);
      
      if (tag) {
        contentControl.tag = tag;
      }
      
      await context.sync();
    });
  }

  public static async onSelectionChanged(callback: (context: Word.RequestContext) => Promise<void>): Promise<void> {
    if (!this.isWordAvailable()) {
      throw new Error('Word is not available');
    }

    // Word插件中的事件监听需要特殊处理
    // 这里提供一个简化的实现
    console.log('Selection change monitoring setup (simplified)');
  }

  public static async getCurrentParagraph(): Promise<Word.Paragraph | null> {
    if (!this.isWordAvailable()) {
      return null;
    }

    return Word.run(async (context) => {
      const selection = context.document.getSelection();
      const paragraph = selection.paragraphs.getFirst();
      paragraph.load('text');
      await context.sync();
      return paragraph;
    });
  }
}